<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of Admins
 *
 * @author phuong
 */
App::uses('SimplePasswordHasher', 'Controller/Component/Auth');

class Admins extends AppModel {

    public $name = 'Admins';
    public $useTable = "admins";
    public $primaryKey = 'AdminId';
    //put your code here
    public $validate = array(
        'AdminId' => array(
            'notEmpty' => array(
                'rule' => array('notEmpty'),
                'message' => 'Not empty',
            ),
        ),
        'AdminName' => array(
            'notEmpty' => array(
                'rule' => array('notEmpty'),
            ),
        ),
        'AdminFurigana' => array(
            'notEmpty' => array(
                'rule' => array('notEmpty'),
            ),
        ),
        'AdminFurigana' => array(
            'notEmpty' => array(
                'rule' => array('notEmpty'),
            ),
        ),
        'AdminPhone' => array(
            'notEmpty' => array(
                'rule' => 'notEmpty',
                'message' => '電話番号を入力してください',
            ),
        ),
        'Email' => array(
            'notEmpty' => array(
                'rule' => array('notEmpty'),
            ),
        ),
        'Pass' => array(
            'notEmpty' => array(
                'rule' => 'notEmpty',
                'message' => 'パスワードを入力してください',
                'on' => 'create'
            ),
        ),
    );

    public function beforeSave($options = array()) {
        parent::beforeSave($options);
        if (!empty($this->data[$this->alias]['Pass'])) {
            $passwordHasher = new SimplePasswordHasher(array('hashType' => 'md5'));
            $this->data[$this->alias]['Pass'] = $passwordHasher->hash(
                    $this->data[$this->alias]['Pass']
            );
        } else {
            unset($this->data[$this->alias]['Pass']);
        }
        return true;
    }

    public function saveData($data, $id = null) {
        if ($id) {
            $this->id = $id;
        } else {
            $this->create();
        }
        $this->set($data);
        if ($this->validates()) {
            return $this->save();
        }
    }

    public function getData($id = null) {
        if (empty($id)) {
            return $this->find('all');
        } else {
            return $this->find('first', array(
                        'conditions' => array('Admins.AdminId ' => $id)
                            )
            );
        }
    }

}
